/*
 * 软件版权: Mr.LEE
 * 修改记录:
 * 修改日期     修改人员  修改说明
 * ========    =======  ============================================
 * 2020/12/23  LJH  新增
 * ========    =======  ============================================
 */
package com.lagou.cloud.service.impl;

import com.lagou.cloud.dao.LagouAuthCodeDao;
import com.lagou.cloud.dao.LagouTokenDao;
import com.lagou.cloud.pojo.LagouAuthCode;
import com.lagou.cloud.pojo.LagouToken;
import com.lagou.cloud.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 功能说明:
 *
 * @author LJH
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;
    @Autowired
    private LagouTokenDao lagouTokenDao;

    @Override
    public boolean register(String email, String password, String token) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(token)) {
            return false;
        }
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(token);
        Example<LagouAuthCode> example = Example.of(lagouAuthCode);
        LagouAuthCode authCode = lagouAuthCodeDao.findOne(example).get();
        Date expireTime = authCode.getExpireTime();
        if (expireTime.before(new Date())) {
            System.out.println("验证码已过期！");
            return false;
        }
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(DigestUtils.md5DigestAsHex(password.getBytes()));
        LagouToken save = lagouTokenDao.save(lagouToken);
        System.out.println(save.toString());
        return true;
    }

    @Override
    public boolean login(String email, String password) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        Example<LagouToken> example = Example.of(lagouToken);
        LagouToken one = lagouTokenDao.findOne(example).get();
        String token = one.getToken();
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        String digestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        return token.equals(digestAsHex);
    }
}
